package com.cc8w.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * 
 * 实现多客户端的链接
 *
 */
public class ServerSocketThreadService extends Thread  {
	private Socket socket = null;
	public ServerSocketThreadService(Socket socket) {
		this.socket = socket;
		
	}
	@Override
	public void run() {		
		
		InputStream is = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		
		OutputStream os = null;
		PrintWriter pw = null;
		try {
			//1.处理并显示客户端发来消息
			is = socket.getInputStream();
			isr = new InputStreamReader(is);
			br = new BufferedReader(isr);
			String info = null;
			while((info = br.readLine())!=null) {
				System.out.println("server: 我接收到了client发来的->"+info);
			}
			socket.shutdownInput();//关闭输入流

			//2.回应客户端消息
			os = socket.getOutputStream();
			pw = new PrintWriter(os);
			System.out.println("server: 给客户端回复-> 你好client,我server收到你信息");
			pw.write("你好client,我server收到你信息");
			pw.flush();
			socket.shutdownOutput();//关闭输出流
			
			
		} catch (IOException e) {
			
			//3.关闭资源
			try {
				//3.1输入流(相关)
				if(br!=null) br.close();
				if(isr!=null) isr.close();
				if(is!=null) is.close();	
				//3.2输出流(相关)
				if(pw!=null) pw.close();
				if(os!=null) os.close();
				//3.3
				socket.close();
			} catch (IOException e1) {

			}

		}
		


		
		
		
	}
	


}
